import Vue from 'vue'
import Router from 'vue-router'
import routes from './routers'
import store from '@/store'
import { Toast } from 'vant';
import { setTitle } from '@/libs/util'
import config from '@/config'
const { homeName } = config

Vue.use(Router)
const router = new Router({
  routes,
  mode: 'history'
})
const LOGIN_PAGE_NAME = 'login'
const REGISTER_PAGE_NAME = 'register'
const CODE_NAME = 'code'
const RESET_NAME = 'repass'
const XIEYI1_NAME = 'xieyi1'
const XIEYI2_NAME = 'xieyi2'

router.beforeEach((to, from, next) => {
  Toast.loading({
    message: '加载中...',
    forbidClick: true
  });
  const userId = store.state.user.userId
  if (!userId && to.name !== LOGIN_PAGE_NAME && to.name !== REGISTER_PAGE_NAME && to.name !== CODE_NAME && to.name !== RESET_NAME && to.name !== XIEYI1_NAME && to.name !== XIEYI2_NAME) {
    // 未登录且要跳转的页面不是登录页也不是注册
    next({
      name: LOGIN_PAGE_NAME // 跳转到登录页
    })
  } else if (!userId && to.name === LOGIN_PAGE_NAME) {
    // 未登陆且要跳转的页面是登录页
    next() // 跳转
  } else if (!userId && to.name === REGISTER_PAGE_NAME) {
    // 未登陆且要跳转的页面是注册页
    next() // 跳转
  } else if (userId && to.name === LOGIN_PAGE_NAME) {
    // 已登录且要跳转的页面是登录页
    next({
      name: homeName // 跳转到homeName页
    })
  } else if (userId && to.name === REGISTER_PAGE_NAME) {
    // 已登录且要跳转的页面是注册页
    next({
      name: homeName // 跳转到homeName页
    })
  } else {
    next()
  }
})

router.afterEach(to => {
  setTitle(to, router.app)
  Toast.clear()
  window.scrollTo(0, 0)
})

export default router
